"""
使用Python3自带的WSGI模块测试WSGI协议
    Django、Flask底层使用的都是WSGI协议
"""
from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server


# WSGI App
def simple_app(environ, start_response):
    """
    :param environ: 用于信息的封装、解包
    :param start_response: http状态码、报文头信息
    :return:
    """
    for k, v in environ.items():
        print("dict的key: {0}; dict的value: {1}".format(k, v))
    print("*" * 100)

    setup_testing_defaults(environ)

    # 返回状态码
    status = '200 OK'
    # 返回报文头
    headers = [('Content-type', 'text/plain; charset=utf-8')]

    start_response(status, headers)

    ret = [("%s: %s\n" % (key, value)).encode("utf-8")
           for key, value in environ.items()]
    return ret  # 返回要求可迭代对象


# 创建WSGI Server
# simple_server.py中已经提供了默认的app: demo_app
# simple_server.py中已经提供了默认调用实例：if __name__ == '__main__'
with make_server('0.0.0.0', 8000, simple_app) as httpd:
    print("Serving on port 8000...")
    httpd.serve_forever()
